package indi.mozping.mydbpool;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * @author by mozping
 * @Classname MyDbPool
 * @Description TODO
 * @Date 2019/2/26 17:18
 */
public class MyDbPool implements MyPool {

    //连接对象容器
    private static LinkedList<Connection> pool = new LinkedList<>();

    public MyDbPool(int capacity) {
        if (capacity > 0) {
            for (int i = 0; i < capacity; i++) {
                pool.addLast(new MyConnectionImpl());
            }
        }
    }


    @Override
    public Connection getConnection(long overtime) throws InterruptedException {
        synchronized (pool) {
            if (overtime < 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                long end = System.currentTimeMillis() + overtime;
                long remain = overtime;
                while (pool.isEmpty() && remain > 0) {
                    pool.wait(remain);
                    remain = end - System.currentTimeMillis();
                }
                Connection conn = null;
                if (!pool.isEmpty()) {
                    conn = pool.removeFirst();
                }
                return conn;
            }
        }

    }

    @Override
    public void releaseConn(Connection connection) {
        if (connection != null) {
            synchronized (pool) {
                pool.addLast(connection);
                pool.notifyAll();
            }
        }
    }
}
